package com.yupi.yuoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.constant.CommonConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.judge.JudgeService;
import com.yupi.yuoj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.yupi.yuoj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.yupi.yuoj.model.entity.Question;
import com.yupi.yuoj.model.entity.QuestionSubmit;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.enums.QuestionSubmitLanguageEnum;
import com.yupi.yuoj.model.enums.QuestionSubmitStatusEnum;
import com.yupi.yuoj.model.vo.QuestionSubmitVO;
import com.yupi.yuoj.model.vo.UserVO;
import com.yupi.yuoj.service.QuestionService;
import com.yupi.yuoj.service.QuestionSubmitService;
import com.yupi.yuoj.mapper.QuestionSubmitMapper;
import com.yupi.yuoj.service.UserService;
import com.yupi.yuoj.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.yupi.yuoj.common.ErrorCode.SYSTEM_ERROR;


/**
* @author wangjia
* @description 针对表【question_submit(题目提交)】的数据库操作Service实现
* @createDate 2023-11-08 19:40:44
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService{
    @Resource
    private QuestionService questionService;
    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private JudgeService judgeService;
    /**
     * 题目提交
     *    直接获取题目提交的请求信息 再逐一取出
     * @param loginUser
     * @param questionSubmitAddRequest
     * @return
     *
     * questionsubmitController获取到了前端的题目提交请求，
     * 调用doQuestionSubmit方法，此方法是获取前端发出的请求信息
     * 将QuestionSubmitAddRequest内的questionId、code、language
     * set进questionsubmit对象实体内
     * userId是从request请求中携带的的user信息得到的
     *
     * 为啥不是直接在将userId放在questionsubmit中呢？
     * 前端在发送请求时就要将获取当前用户信息id，一起发送作为题目提交的字段，
     * 这样子就不解耦了，题目提交就只发送题目相关的字段，对于用户信息就http请求字段中发
     * 这也是这个模板考虑到的，用户信息获取以后也就不用再写了
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        //  检验编程语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if(languageEnum == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"编程语言错误");
        }
        // 判断实体是否存在，根据类别获取实体
        long questionId = questionSubmitAddRequest.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已题目提交
        long userId = loginUser.getId();
        // 每个用户串行题目提交
        // 创建一个questionsubmit对象，用于存储题目提交的信息
        // 在数据库中就对应着在questionsubmit表中创建一行并填充字段
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(language);
        // 设置初始状态
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());

        questionSubmit.setJudgeInfo("{}");
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(SYSTEM_ERROR, "数据插入失败");
        }
        Long questionSubmitId = questionSubmit.getId();
        //  执行判题服务
        CompletableFuture.runAsync(()->{
            judgeService.doJudge(questionSubmitId);
        });


        return questionSubmitId ;
    }



    /**
     * 获取查询包装类(根据前端传来的请求对象，使用Mybatis框架支持的查询QueryWapper类)
     * 1、定义：QueryWrapper是MyBatis框架中的一个实用工具类
     * 2、作用：QueryWrapper用于动态拼接 构建查询条件，来对数据库进行操作
     *    如条件eq、ne、gt、ge、lt、le等方法来表示
     *    等于、不等于、大于、大于等于、小于、小于等于等各种条件，还可以进行模糊查询、in查询等
     *
     *
     *
     * @param questionSubmitQueryRequest
     * @return
     */

//    使用QueryWrapper构建查询条件 查询数据库 并返回查询结果
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();

        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();


        //拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);

        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    /**
     *   查询-单条-题目提交信息
     * @param questionSubmit
     * @param loginUser
     * @return
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);

        long userId = loginUser.getId();
        //处理脱敏 仅本人和管理员可那件提交的代码
        if(userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)){
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    /**
     *   查询-分页-题目提交信息
     * @param questionSubmitPage
     * @param loginUser
     * @return
     */

//    作用：将QuestionSubmit对象转换为QuestionSubmitVO对象
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        //Page对象包含分页信息和记录列表，通过 getRecords() 方法获取到记录列表。
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        //创建一新 Page 对象 questionSubmitVOPage，它的当前页、每页大小和总记录数与原来的 questionSubmitPage 相同。
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        //检查questionSubmitPage的记录列表是否为空，空就直接返回一个新建的三同的questionSubmitVOPage
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }

        /**
         * 使用流式处理（stream）和 map 操作，将 questionSubmitList 中的
         * 每个 QuestionSubmit 对象转换为 QuestionSubmitVO 对象，
         * 转换逻辑由 getQuestionSubmitVO 方法完成
         *      --->也就是针对用户身份进行脱敏处理
         * 最后使用 collect(Collectors.toList()) 将转换后的对象收集为列表
         */
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

}




